package com.ChenYaRou.www.controller;

import com.ChenYaRou.www.constant.JsonBeanConstant;
import com.ChenYaRou.www.dao.DetailedUserDao;
import com.ChenYaRou.www.dao.FoodDao;
import com.ChenYaRou.www.dao.ShopDao;
import com.ChenYaRou.www.dao.impl.DetailedUserDaoImpl;
import com.ChenYaRou.www.dao.impl.FoodDapImpl;
import com.ChenYaRou.www.dao.impl.ShopDaoImpl;
import com.ChenYaRou.www.po.*;
import com.ChenYaRou.www.utils.GenerateSql;
import com.ChenYaRou.www.utils.JsonBean;
import com.ChenYaRou.www.utils.UpdateOrInsertOrSelectMoreAllBean;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import static com.ChenYaRou.www.constant.Constant.*;
import static com.ChenYaRou.www.constant.False.EMPTY;
import static com.ChenYaRou.www.constant.JsonBeanConstant.SUCCESS;


/**
 * @ClassName IntoShopServletController
 * @Description TODO
 * @Author 86183
 * @Date 2022/5/1 23:45
 * @Version 1.0
 **/
public class ShopServletController {
    /**
     * 进入店铺后 通过店铺id 获得店铺的美食信息
     * @param shopId
     * @return
     */
    public String getTheShopAndFood(Integer shopId){
        if(shopId!=null){
            Food food = new Food();
            food.setShopId(shopId);
            List<Object> list=new ArrayList<>();
            try {
                ShopDao shopDao=new ShopDaoImpl();
                Shop shop=new Shop();
                shop.setId(shopId);
                shop = shopDao.selectSingle(shop);
                list.add(shop);
            } catch (IllegalAccessException | SQLException | NoSuchFieldException | InstantiationException e) {
                e.printStackTrace();
            }
            list.add(UpdateOrInsertOrSelectMoreAllBean.getInstance().selectMore(food));
            return JsonBean.operateList(JsonBeanConstant.NULL,list);
        }
        return JsonBean.operateList(JsonBeanConstant.FRONT_ERROR,null);
    }

    /**
     *
     * @param ownerId
     * @return
     */
    public String getTheShopAndFoodByOwnerId(Integer ownerId){
        if(ownerId!=null){
            Food food = new Food();
            List<Object> list=new ArrayList<>();
            try {

                ShopDao shopDao=new ShopDaoImpl();
                Shop shop=new Shop();
                shop.setOwnerId(ownerId);
                Shop theShop = shopDao.selectSingle(shop);
                list.add(theShop);

                food.setShopId(theShop.getId());
            } catch (IllegalAccessException | SQLException | NoSuchFieldException | InstantiationException e) {
                e.printStackTrace();
            }
            list.add(UpdateOrInsertOrSelectMoreAllBean.getInstance().selectMore(food));
            return JsonBean.operateList(JsonBeanConstant.NULL,list);
        }
        return JsonBean.operateList(JsonBeanConstant.FRONT_ERROR,null);
    }

    /**
     * 点击收藏 添加收藏
     * @param collection
     * @return
     */
    public String addCollection(Collection collection){
        return UpdateOrInsertOrSelectMoreAllBean.getInstance().insert(collection);
    }

    /**
     * 更新店铺设置
     * @param
     * @return
     */
    public void updateShop(HttpServletRequest request,HttpServletResponse response){
        try {
            String shopId = request.getParameter("shopId");
            String name = request.getParameter("name");
            String introduction = request.getParameter("introduction");
            String money = request.getParameter("money");
            String district = request.getParameter("district");
            String street = request.getParameter("street");
            String detailAddress = request.getParameter("detailAddress");
            if(EMPTY.equals(money)) {
                response.sendRedirect("Seller.jsp?state=money could not be empty");
            }
            if(Float.parseFloat(String.valueOf(money))<0){
                response.sendRedirect("Seller.jsp?state=money could not be a negative");
                return;}
            Shop shop = new Shop();
            shop.setName(name);
            shop.setIntroduction(introduction);
            shop.setMoney(Float.parseFloat(money));
            shop.setDistrictName(district);
            shop.setStreetName(street);
            shop.setDetailedAddress(detailAddress);
            makePicture(request,shop);
            Shop shopOld = new Shop();
            shopOld.setId(Integer.valueOf(shopId));
            ShopDao shopDao=new ShopDaoImpl();
            int insert = shopDao.update(shop,shopOld);
            if(insert>0){
                response.sendRedirect("Seller.jsp?state="+SUCCESS);
            }else{
                response.sendRedirect("Seller.jsp?state=fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新已有菜单设置
     * @param
     * @return
     */
    public void updateFood(HttpServletRequest request, HttpServletResponse response){
        try {
            Object foodId = request.getParameter("foodId");
            Object name = request.getParameter("name");
            Object price = request.getParameter("price");
            if(EMPTY.equals(name)){
                response.sendRedirect("Seller.jsp?state=name could not be empty");
                return;
            }
            if(EMPTY.equals(price)){
                response.sendRedirect("Seller.jsp?state=price could not be empty");
                return;
            }
            if(Float.parseFloat(String.valueOf(price))<0){
                response.sendRedirect("Seller.jsp?state=price could not be a negative");
                return;}
            Food food = new Food();
            food.setId(Integer.parseInt(String.valueOf(foodId)));
            food.setName(String.valueOf(name));
            food.setPrice(Float.parseFloat(String.valueOf(price)));
            makePicture(request,food);
            Food oldFood=new Food();
            oldFood.setId(food.getId());
            FoodDao foodDao=new FoodDapImpl();
            int insert = foodDao.update(food,oldFood);
            if(insert>0){
                response.sendRedirect("Seller.jsp?state="+SUCCESS);
            }else{
                response.sendRedirect("Seller.jsp?state=fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增菜谱
     * @param food
     * @return
     */
    public String insertFood(Food food){
        return UpdateOrInsertOrSelectMoreAllBean.getInstance().insert(food);
    }

    /**
     * 新增美食
     * @param request
     * @param response
     */
    public void insertNewFood(HttpServletRequest request, HttpServletResponse response){
        try {
            Object shopId = request.getParameter("shopId");
            Object name = request.getParameter("name");
            Object price = request.getParameter("price");
            if(EMPTY.equals(name)){
                response.sendRedirect("Seller.jsp?state=name could not be empty");
                return;
            }
            if(EMPTY.equals(price)){
                response.sendRedirect("Seller.jsp?state=price could not be empty");
                return;
            }
            if(Float.parseFloat(String.valueOf(price))<0){
                response.sendRedirect("Seller.jsp?state=price could not be a negative");
                return;}
            System.out.println(shopId);
            System.out.println(name);
            System.out.println(price);
            Food food = new Food(
                    name.toString(),Float.parseFloat(String.valueOf(price)), Integer.parseInt(String.valueOf(shopId)));
            makePicture(request,food);
            FoodDao foodDao=new FoodDapImpl();
            int insert = foodDao.insert(food);
            System.out.println(food);
            System.out.println(insert);
            if(insert>0){
                response.sendRedirect("Seller.jsp?state="+SUCCESS);
            }else{
                response.sendRedirect("Seller.jsp?state=fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String updateOrders(Orders orders){
        if(orders!=null){
            try {
                if(OVER.equals(orders.getState())){
                    Shop shop=new Shop();
                    shop.setId(orders.getShopId());

                    ShopDao shopDao=new ShopDaoImpl();
                    Shop shopGet = shopDao.selectSingle(shop);
                    shop.setMoney(shopGet.getMoney()+orders.getCost());

                    Orders ordersOld=new Orders();
                    ordersOld.setId(orders.getId());
                    String updateOrders= GenerateSql.getInstance().update(orders,ordersOld);
                    String updateShop = GenerateSql.getInstance().update(shop,shopGet);
                    return UpdateOrInsertOrSelectMoreAllBean.getInstance().insertOrUpdateMore(updateOrders,updateShop);
                }else if(REFUSE.equals(orders.getState())){
                    Orders ordersOld=new Orders();
                    ordersOld.setId(orders.getId());
                    String updateOrders= GenerateSql.getInstance().update(orders,ordersOld);

                    DetailedUserDao detailedUserDao=new DetailedUserDaoImpl();
                    DetailedUser detailedUser = detailedUserDao.select(orders.getBuyerId());
                    DetailedUser detailedUserNew=new DetailedUser();
                    detailedUserNew.setMoney(detailedUser.getMoney()+orders.getCost());

                    String updateUser=GenerateSql.getInstance().update(detailedUserNew,detailedUser);
                    return UpdateOrInsertOrSelectMoreAllBean.getInstance().insertOrUpdateMore(updateOrders,updateUser);
                }
            } catch (IllegalAccessException | SQLException | NoSuchFieldException | InstantiationException e) {
                e.printStackTrace();
            }
        }
        return JsonBean.operateList(JsonBeanConstant.FRONT_ERROR,null);
    }

    /**
     * 图片添加操作
     * @param request
     * @param object
     * @param <K>
     * @throws ServletException
     * @throws IOException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public  <K> void makePicture(HttpServletRequest request,K object) throws ServletException, IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        // 1. 获取Part对象 request.getPart("name"); name代表的是file文件域的name属性值
        Part part = request.getPart("pictureUrl");
        // 2. 通过Part对象获取上传文件的文件名 (从头部信息中获取上传的文件名)
        String header = part.getHeader("Content-Disposition");
        // 获取具体的请求头对应的值
        String str = header.substring(header.lastIndexOf("=") + 2);
        // 获取上传的文件名
        String fileName = str.substring(0, str.length() - 1);
        // 3. 判断文件名是否为空
        Class<?> aClass = object.getClass();
        Method method = aClass.getDeclaredMethod("setPicture",String.class);
        method.setAccessible(true);
        if(!StringUtils.isNullOrEmpty(fileName)){
            method.invoke(object,fileName);
            // 4. 获取文件存放的路径
            String filePath = request.getServletContext().getRealPath("/picture/upload/");
            // 5. 上传文件到指定目录
            part.write(filePath + "/" + fileName);
        }else{
            method.invoke(object,"图片.png");
        }
    }
}
